package com.tianji.learning.handler;

import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.learning.constants.LearningConstants;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.utils.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class PointBoardPersistentHandler {
    private final IPointsBoardService iPointsBoardService;
    private final IPointsBoardSeasonService seasonService;
    private final StringRedisTemplate redisTemplate;

    /**
     * 定时任务：将赛季积分榜持久化至DB
     */
    @XxlJob("savePointBoard2DB")
    public void savePointBoard2DB(){
        //1.获取一个月前的时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);
        //2.计算动态表名
        Integer season=seasonService.querySeasonByTime(time);

        TableInfoContext.setTL(LearningConstants.POINTS_BOARD_TABLE_PREFIX +season);
        //拼接key
        String key=RedisConstants.BOARD_RECORD_KEY_PREFIX+time.format(DateUtils.POINT_BOARD_SUFFIX_FORMATTER);
        //3.查询
        int index = XxlJobHelper.getShardIndex();
        int total = XxlJobHelper.getShardTotal();
        // 起始页，就是分片序号+1
        int pageNo = index + 1;
        int pageSize=10;
        while (true){
            List<PointsBoard> boards = iPointsBoardService.queryCurrentList(key, pageNo, pageSize);
            if(CollUtils.isEmpty(boards)){
                break;
            }
            //4.持久化至数据库
            boards.forEach(b->{
                b.setId(b.getRank().longValue());
                b.setRank(null);
            });

            iPointsBoardService.saveBatch(boards);
            //5.下一页
            pageNo+=total;
        }
        //移除动态表名
        TableInfoContext.remove();

    }

    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis(){
        // 1.获取上月时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);
        // 2.计算key
        String key = RedisConstants.BOARD_RECORD_KEY_PREFIX + time.format(DateUtils.POINT_BOARD_SUFFIX_FORMATTER);
        // 3.删除
        redisTemplate.unlink(key);
    }

}
